<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="SPU名称">
        <el-input
          type="text"
          placeholder="请输入SPU名称"
          v-model="spuParams.spuName"
        />
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择" v-model="spuParams.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="(trademark, index) in trademarkList"
            :key="trademark.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="spuParams.description"
        />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="changeHandler"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible" width="25%">
          <img
            w-full
            :src="dialogImageUrl"
            style="width: 400px; height: 400px"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="
            unHasSaleAttr.length > 0
              ? `您还有${unHasSaleAttr.length}个未选择`
              : '已经没有了'
          "
          v-model="saleAttrData"
          :disabled="!unHasSaleAttr.length"
        >
          <el-option
            :label="saleAttr.name"
            :value="`${saleAttr.id}:${saleAttr.name}`"
            v-for="(saleAttr, index) in unHasSaleAttr"
            :key="saleAttr.id"
          />
        </el-select>
        <el-button
          type="primary"
          :icon="Plus"
          style="margin-left: 20px"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table border :data="spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          />
          <el-table-column prop="saleAttrName" label="属性名" width="160px" />
          <el-table-column label="属性值名称列表">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 0 5px"
                :type="saleAttrValue.id % 2 == 0 ? 'success' : ''"
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                >{{ saleAttrValue.saleAttrValueName }}</el-tag
              >
              <el-input
                v-if="row.flag"
                type="text"
                size="small"
                style="width: 150px"
                @blur="toLook(row)"
                v-model="row.saleAttrValueName"
                :ref="(el) => (inputRef[$index] = el)"
              />
              <el-button
                v-else
                type="primary"
                :icon="Plus"
                size="small"
                @click="toEdit(row, $index)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160px" />
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpu">保存</el-button>
        <el-button @click="cancelHandler">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";

import {
  reqBaseSaleAttrList,
  reqTrademarkList,
  reqSpuSaleAttrList,
  reqSpuImageList,
  reqAddOrUpdateSpu,
} from "@/api/product/Spu"; // 请求函数
import type {
  IBaseSaleAttrList,
  ITrademarkList,
  ISpuSaleAttrList,
  ISpuImageList,
  ISpuData,
} from "@/api/product/Spu/model"; // 数据类型

const emit = defineEmits(["changeScene"]);
const baseSaleAttrList = ref<IBaseSaleAttrList>([]); // 基础销售属性数据
const trademarkList = ref<ITrademarkList>([]); // 品牌数据
const spuSaleAttrList = ref<ISpuSaleAttrList>([]); // spu销售属性数据
const spuImageList = ref<UploadUserFile[]>([]); // spu图片数据
const saleAttrData = ref<string>(""); // 销售属性的名称与id
const inputRef = ref([]); // 所有属性值input框的实例

const spuParams = ref({
  category3Id: "",
  description: "",
  id: "",
  spuImageList: null,
  spuName: "",
  spuSaleAttrList: null,
  tmId: "",
}); // 添加或修改spu需要的参数

// 计算未选择的销售属性
const unHasSaleAttr = computed(() => {
  return baseSaleAttrList.value.filter((baseAttr) => {
    return spuSaleAttrList.value.every((saleAttr) => {
      return baseAttr.id != saleAttr.baseSaleAttrId;
    });
  });
});

/**********  照片相关的代码  *************/
const dialogImageUrl = ref(""); // 图片地址
const dialogVisible = ref(false); // dialog对话框的状态

// 删除图片的回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  spuImageList.value = uploadFiles;
};

// 预览图片的回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 添加图片时的回调
const changeHandler = (uploadFile, uploadFiles) => {
  spuImageList.value = uploadFiles;
};
/***************************************/

// 修改spu, 获取spu数据
const getSpuData = async (spu: ISpuData) => {
  spuParams.value = spu;
  const baseSaleAttrListData = reqBaseSaleAttrList();
  const trademarkListData = reqTrademarkList();
  const spuSaleAttrListData = reqSpuSaleAttrList(spu.id);
  const spuImageListData = reqSpuImageList(spu.id);

  const result = await Promise.all([
    baseSaleAttrListData,
    trademarkListData,
    spuSaleAttrListData,
    spuImageListData,
  ]);

  baseSaleAttrList.value = result[0];
  trademarkList.value = result[1];
  spuSaleAttrList.value = result[2];
  spuImageList.value = result[3].map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
};

// 添加销售属性按钮的回调
const addSaleAttr = () => {
  if (!saleAttrData.value) return;
  const [baseSaleAttrId, saleAttrName] = saleAttrData.value.split(":");
  spuSaleAttrList.value.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  });
  saleAttrData.value = "";
};

// input失焦切花查看模式
const toLook = (row) => {
  if (!row.saleAttrValueName) {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    row.flag = false;
    return;
  }

  const result = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == row.saleAttrValueName;
  });

  if (result) {
    ElMessage({
      type: "error",
      message: "属性值已存在",
    });
    row.flag = false;
    return;
  }

  row.flag = false;
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrName: row.saleAttrName,
    saleAttrValueName: row.saleAttrValueName,
  });
};

// 点击按钮切换编辑模式
const toEdit = (row, index) => {
  row.flag = true;
  row.saleAttrValueName = "";
  nextTick(() => {
    inputRef.value[index].focus();
  });
};

// 保存spu按钮的回调
const saveSpu = async () => {
  spuParams.value.spuImageList = spuImageList.value.map((item) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });

  spuSaleAttrList.value.forEach((item) => {
    if (item.flag) {
      delete item.flag;
    }
    if (item.saleAttrValueName) {
      delete item.saleAttrValueName;
    }
  });
  spuParams.value.spuSaleAttrList = spuSaleAttrList.value;

  try {
    await reqAddOrUpdateSpu(spuParams.value);

    ElMessage({
      type: "success",
      message: spuParams.value.id ? "修改成功" : "添加成功",
    });
    emit("changeScene", { cutScene: 0, flag: spuParams.value.id });
  } catch (error) {
    ElMessage({
      type: "error",
      message: spuParams.value.id ? "修改失败" : "添加失败",
    });
  }
};

// 获取添加spu所需的数据
const getAddSpuData = async (category3Id) => {
  spuParams.value.category3Id = category3Id;
  const baseSaleAttrListData = reqBaseSaleAttrList();
  const trademarkListData = reqTrademarkList();
  const result = await Promise.all([baseSaleAttrListData, trademarkListData]);
  baseSaleAttrList.value = result[0];
  trademarkList.value = result[1];
};

// 清空添加或修改spu时所需的数据
const clearSpuData = () => {
  baseSaleAttrList.value = [];
  trademarkList.value = [];
  spuSaleAttrList.value = [];
  spuImageList.value = [];
  spuParams.value = {
    category3Id: "",
    description: "",
    id: "",
    spuImageList: null,
    spuName: "",
    spuSaleAttrList: null,
    tmId: "",
  };
};

// 取消按钮的回调
const cancelHandler = () => {
  emit("changeScene", { cutScene: 0, flag: 0 });
  clearSpuData();
};

// 对外暴露方法
defineExpose({
  getSpuData,
  getAddSpuData,
  cancelHandler,
});
</script>
